/**
 * 分享卡片预生成服务
 * 在诗词和配图生成完成后，后台预生成分享卡片并缓存
 */

// 缓存存储
const shareCardCache = new Map()
const backgroundImageCache = new Map()

// 性能统计
let performanceStats = {
  totalRequests: 0,
  cacheHits: 0,
  cacheMisses: 0,
  hitRate: 0,
  avgGenerationTime: 0,
  avgRetrievalTime: 0,
  currentCacheSize: 0,
  recentActivity: [],
  generationTimes: [],
  retrievalTimes: []
}

// 性能监听器
const performanceListeners = new Set()

// 添加活动记录
const addActivity = (type, description, duration = 0) => {
  const activity = {
    type,
    description,
    duration,
    timestamp: Date.now()
  }
  
  performanceStats.recentActivity.unshift(activity)
  
  // 保持最新20条记录
  if (performanceStats.recentActivity.length > 20) {
    performanceStats.recentActivity = performanceStats.recentActivity.slice(0, 20)
  }
  
  // 通知所有监听器
  performanceListeners.forEach(listener => {
    try {
      listener()
    } catch (error) {
      console.warn('性能监听器错误:', error)
    }
  })
}

// 更新统计数据
const updateStats = () => {
  const total = performanceStats.cacheHits + performanceStats.cacheMisses
  performanceStats.totalRequests = total
  performanceStats.hitRate = total > 0 ? (performanceStats.cacheHits / total) * 100 : 0
  performanceStats.currentCacheSize = shareCardCache.size
  
  // 计算平均时间
  if (performanceStats.generationTimes.length > 0) {
    performanceStats.avgGenerationTime =
      performanceStats.generationTimes.reduce((a, b) => a + b, 0) / performanceStats.generationTimes.length
  }
  
  if (performanceStats.retrievalTimes.length > 0) {
    performanceStats.avgRetrievalTime =
      performanceStats.retrievalTimes.reduce((a, b) => a + b, 0) / performanceStats.retrievalTimes.length
  }
}

/**
 * 格式化诗句为四行显示
 * @param {string} poem - 诗句内容
 * @returns {Array} - 格式化后的行数组
 */
const formatPoemLines = (poem) => {
  if (!poem) return []

  // 移除多余的空白字符，但保留换行符
  const cleanPoem = poem.replace(/[ \t]+/g, '').replace(/\n+/g, '\n')

  // 先按换行符分割
  let lines = cleanPoem.split('\n').filter(line => line.trim())

  // 如果行数不是4行，尝试重新分割
  if (lines.length !== 4) {
    // 合并所有文本
    const fullText = lines.join('')

    // 按标点符号分割
    const parts = fullText.split(/([，。！？；：])/g).filter(part => part.trim())

    // 重新组合成行
    const newLines = []
    let currentLine = ''

    for (let i = 0; i < parts.length; i++) {
      const part = parts[i]

      if (/[，。！？；：]/.test(part)) {
        // 是标点符号，加到当前行并结束这一行
        currentLine += part
        if (currentLine.trim()) {
          newLines.push(currentLine.trim())
          currentLine = ''
        }
      } else {
        // 是文字内容
        currentLine += part
      }
    }

    // 处理剩余内容
    if (currentLine.trim()) {
      newLines.push(currentLine.trim())
    }

    // 如果还是不是4行，进行调整
    if (newLines.length > 0) {
      if (newLines.length > 4) {
        // 超过4行，合并后面的行
        lines = newLines.slice(0, 3)
        lines.push(newLines.slice(3).join(''))
      } else if (newLines.length < 4 && newLines.length >= 2) {
        // 少于4行但有内容，尝试拆分长行
        lines = []
        for (const line of newLines) {
          if (line.length > 12 && lines.length < 3) {
            // 尝试在合适的位置拆分
            const mid = Math.floor(line.length / 2)
            let splitPos = mid

            // 寻找最近的标点符号作为分割点
            for (let j = mid; j < line.length && j < mid + 5; j++) {
              if (/[，。！？；：]/.test(line[j])) {
                splitPos = j + 1
                break
              }
            }

            lines.push(line.substring(0, splitPos))
            lines.push(line.substring(splitPos))
          } else {
            lines.push(line)
          }
        }

        // 确保不超过4行
        if (lines.length > 4) {
          const temp = lines.slice(0, 3)
          temp.push(lines.slice(3).join(''))
          lines = temp
        }
      } else {
        lines = newLines
      }
    }
  }

  // 限制最多4行
  if (lines.length > 4) {
    lines = lines.slice(0, 4)
  }

  return lines
}

/**
 * 使用代理服务获取背景图片数据
 * @param {string} imageUrl - 原始图片URL
 * @returns {Promise<string>} - base64 data URL
 */
const fetchImageWithProxy = async (imageUrl) => {
  // 更新的CORS代理服务列表，优先使用稳定的服务
  const CORS_PROXIES = [
    'https://corsproxy.io/?',
    'https://api.codetabs.com/v1/proxy?quest=',
    'https://api.allorigins.win/raw?url=',
    'https://cors-proxy.htmldriven.com/?url=',
    'https://thingproxy.freeboard.io/fetch/'
  ]

  console.log('🔄 尝试使用代理获取背景图片:', imageUrl)

  // 首先尝试直接获取（对于BFL delivery域名）
  if (imageUrl.includes('delivery-') && imageUrl.includes('.bfl.ai')) {
    try {
      console.log('🎯 BFL delivery域名，尝试直接获取')
      const response = await fetch(imageUrl, {
        mode: 'cors',
        headers: {
          'Accept': 'image/*'
        }
      })
      if (response.ok) {
        const blob = await response.blob()
        return new Promise((resolve) => {
          const reader = new FileReader()
          reader.onload = () => resolve(reader.result)
          reader.readAsDataURL(blob)
        })
      }
    } catch (error) {
      console.log('📝 直接获取失败，尝试代理:', error.message)
    }
  }

  // 使用代理服务
  for (const proxy of CORS_PROXIES) {
    try {
      let proxiedUrl
      if (proxy.includes('corsproxy.io')) {
        proxiedUrl = `${proxy}${encodeURIComponent(imageUrl)}`
      } else if (proxy.includes('codetabs.com')) {
        proxiedUrl = `${proxy}${encodeURIComponent(imageUrl)}`
      } else if (proxy.includes('allorigins.win')) {
        proxiedUrl = `${proxy}${encodeURIComponent(imageUrl)}`
      } else if (proxy.includes('htmldriven.com')) {
        proxiedUrl = `${proxy}${encodeURIComponent(imageUrl)}`
      } else {
        proxiedUrl = `${proxy}${imageUrl}`
      }

      console.log('🔄 尝试代理:', proxiedUrl.substring(0, 100) + '...')

      const response = await fetch(proxiedUrl, {
        headers: {
          'Accept': 'image/*'
        }
      })

      if (response.ok) {
        const blob = await response.blob()
        console.log('✅ 代理获取成功:', proxy)
        return new Promise((resolve) => {
          const reader = new FileReader()
          reader.onload = () => resolve(reader.result)
          reader.readAsDataURL(blob)
        })
      }
    } catch (error) {
      console.warn(`⚠️ 代理 ${proxy} 失败:`, error.message)
    }
  }

  throw new Error('所有代理都无法获取图片')
}

/**
 * 预缓存背景图片，避免跨域问题
 * @param {string} imageUrl - 原始图片URL
 * @param {string} cacheKey - 缓存键
 * @returns {Promise<string>} - base64 data URL
 */
const precacheBackgroundImage = async (imageUrl, cacheKey) => {
  if (backgroundImageCache.has(cacheKey)) {
    console.log('📦 使用缓存的背景图片')
    return backgroundImageCache.get(cacheKey)
  }

  try {
    console.log('🎨 开始预缓存背景图片:', imageUrl?.substring(0, 100) + '...')

    // 验证图片URL
    if (!imageUrl || typeof imageUrl !== 'string') {
      throw new Error('无效的图片URL')
    }

    // 如果是本地blob URL或data URL，直接使用
    if (imageUrl.startsWith('blob:') || imageUrl.startsWith('data:')) {
      console.log('✅ 本地图片，直接缓存')
      backgroundImageCache.set(cacheKey, imageUrl)
      return imageUrl
    }

    // 使用代理获取图片数据
    const dataUrl = await fetchImageWithProxy(imageUrl)
    if (dataUrl && dataUrl.startsWith('data:')) {
      backgroundImageCache.set(cacheKey, dataUrl)
      console.log('✅ 背景图片预缓存成功')
      return dataUrl
    } else {
      throw new Error('获取的数据不是有效的data URL')
    }

  } catch (error) {
    console.warn('⚠️ 背景图片预缓存失败:', error.message)
    // 返回null表示失败，将使用默认背景
    return null
  }
}

/**
 * 预生成分享卡片
 * @param {Object} params - 生成参数
 * @param {string} params.poem - 诗句
 * @param {string} params.emotion - 情绪
 * @param {string} params.userInput - 用户输入
 * @param {Object} params.generatedImage - 生成的图片信息
 * @returns {Promise<string>} - 分享卡片的data URL
 */
const pregenerateShareCard = async ({ poem, emotion, userInput, generatedImage }) => {
  const startTime = performance.now()
  const cacheKey = `${poem}-${emotion}-${userInput}`.slice(0, 100)
  
  // 检查是否已经缓存
  if (shareCardCache.has(cacheKey)) {
    console.log('📱 使用缓存的分享卡片')
    const retrievalTime = performance.now() - startTime
    performanceStats.cacheHits++
    performanceStats.retrievalTimes.push(retrievalTime)
    if (performanceStats.retrievalTimes.length > 100) {
      performanceStats.retrievalTimes = performanceStats.retrievalTimes.slice(-100)
    }
    addActivity('cache_hit', '使用缓存的分享卡片', retrievalTime)
    updateStats()
    return shareCardCache.get(cacheKey)
  }

  performanceStats.cacheMisses++
  try {
    console.log('🎨 开始预生成分享卡片...')
    console.log('📋 输入参数:', {
      poem: poem?.substring(0, 30) + '...',
      emotion,
      userInput: userInput?.substring(0, 30) + '...',
      hasGeneratedImage: !!generatedImage?.success,
      imageUrl: generatedImage?.imageUrl?.substring(0, 50) + '...'
    })

    // 验证必要参数
    if (!poem || !emotion) {
      throw new Error('缺少必要参数：诗句或情绪')
    }

    // 创建canvas
    const canvas = document.createElement('canvas')
    const ctx = canvas.getContext('2d')

    if (!ctx) {
      throw new Error('无法创建Canvas上下文')
    }

    // 设置画布尺寸 (适合社交媒体分享的比例)
    canvas.width = 800
    canvas.height = 1000

    // 清空画布
    ctx.clearRect(0, 0, canvas.width, canvas.height)

    // 预缓存背景图片
    let backgroundImageUrl = null
    if (generatedImage?.success && generatedImage.imageUrl) {
      console.log('🖼️ 检测到生成的图片，开始预缓存背景图片')
      console.log('📸 图片URL:', generatedImage.imageUrl.substring(0, 100) + '...')

      const imgCacheKey = `bg-${generatedImage.imageUrl.substring(0, 50)}`
      backgroundImageUrl = await precacheBackgroundImage(generatedImage.imageUrl, imgCacheKey)
      console.log('🖼️ 背景图片预缓存结果:', backgroundImageUrl ? '成功' : '失败')
    } else {
      console.log('⚠️ 没有检测到生成的图片，将使用默认背景')
    }

    // 绘制背景
    console.log('🎨 开始绘制背景...')
    await drawShareCardBackground(ctx, canvas, backgroundImageUrl)

    // 绘制内容
    console.log('✍️ 开始绘制内容...')
    drawShareCardContent(ctx, canvas, poem, emotion, userInput)

    // 转换为data URL并缓存
    console.log('📸 转换为图片格式...')
    const dataUrl = canvas.toDataURL('image/jpeg', 0.9)

    if (!dataUrl || !dataUrl.startsWith('data:image/')) {
      throw new Error('Canvas转换失败，生成的不是有效的图片数据')
    }

    shareCardCache.set(cacheKey, dataUrl)

    const generationTime = performance.now() - startTime
    console.log('✅ 分享卡片预生成完成，耗时:', generationTime.toFixed(1) + 'ms')

    // 记录生成时间
    performanceStats.generationTimes.push(generationTime)
    if (performanceStats.generationTimes.length > 100) {
      performanceStats.generationTimes = performanceStats.generationTimes.slice(-100)
    }

    addActivity('pregeneration', '分享卡片预生成完成', generationTime)
    updateStats()

    return dataUrl

  } catch (error) {
    console.error('❌ 分享卡片预生成失败:', error)
    console.error('错误堆栈:', error.stack)
    addActivity('error', `分享卡片预生成失败: ${error.message}`, performance.now() - startTime)
    return null
  }
}

/**
 * 绘制分享卡片背景
 * @param {CanvasRenderingContext2D} ctx - Canvas上下文
 * @param {HTMLCanvasElement} canvas - Canvas元素
 * @param {string} backgroundImageUrl - 背景图片URL
 */
const drawShareCardBackground = async (ctx, canvas, backgroundImageUrl) => {
  if (backgroundImageUrl && (backgroundImageUrl.startsWith('data:') || backgroundImageUrl.startsWith('blob:'))) {
    try {
      console.log('🖼️ 开始绘制背景图片')
      const img = new Image()

      // 设置超时机制，避免长时间等待
      const loadPromise = new Promise((resolve, reject) => {
        const timeout = setTimeout(() => {
          img.onload = null
          img.onerror = null
          reject(new Error('图片加载超时'))
        }, 10000) // 10秒超时

        img.onload = () => {
          clearTimeout(timeout)
          console.log('✅ 背景图片加载成功，尺寸:', img.width, 'x', img.height)
          resolve()
        }

        img.onerror = (error) => {
          clearTimeout(timeout)
          console.error('❌ 背景图片加载失败:', error)
          reject(new Error('图片加载失败'))
        }

        // 对于data URL，不需要设置crossOrigin
        if (!backgroundImageUrl.startsWith('data:')) {
          img.crossOrigin = 'anonymous'
        }

        img.src = backgroundImageUrl
      })

      await loadPromise

      // 验证图片尺寸
      if (img.width === 0 || img.height === 0) {
        throw new Error('图片尺寸无效')
      }

      // 绘制背景图片，保持比例并居中
      const scale = Math.max(canvas.width / img.width, canvas.height / img.height)
      const scaledWidth = img.width * scale
      const scaledHeight = img.height * scale
      const x = (canvas.width - scaledWidth) / 2
      const y = (canvas.height - scaledHeight) / 2

      // 保存当前状态
      ctx.save()

      // 绘制图片
      ctx.drawImage(img, x, y, scaledWidth, scaledHeight)
      console.log('🎨 背景图片绘制完成')

      // 添加半透明遮罩，让文字更清晰
      ctx.fillStyle = 'rgba(0, 0, 0, 0.4)'
      ctx.fillRect(0, 0, canvas.width, canvas.height)

      // 恢复状态
      ctx.restore()

    } catch (error) {
      console.warn('⚠️ 背景图片绘制失败，使用默认背景:', error.message)
      drawDefaultBackground(ctx, canvas)
    }
  } else {
    console.log('🎨 没有背景图片或图片格式不支持，使用默认背景')
    drawDefaultBackground(ctx, canvas)
  }
}

/**
 * 绘制默认背景
 * @param {CanvasRenderingContext2D} ctx - Canvas上下文
 * @param {HTMLCanvasElement} canvas - Canvas元素
 */
const drawDefaultBackground = (ctx, canvas) => {
  // 渐变背景
  const gradient = ctx.createLinearGradient(0, 0, canvas.width, canvas.height)
  gradient.addColorStop(0, '#f7fafc')
  gradient.addColorStop(0.5, '#edf2f7')
  gradient.addColorStop(1, '#e2e8f0')

  ctx.fillStyle = gradient
  ctx.fillRect(0, 0, canvas.width, canvas.height)
}

/**
 * 绘制分享卡片内容
 * @param {CanvasRenderingContext2D} ctx - Canvas上下文
 * @param {HTMLCanvasElement} canvas - Canvas元素
 * @param {string} poem - 诗句
 * @param {string} emotion - 情绪
 * @param {string} userInput - 用户输入
 */
const drawShareCardContent = (ctx, canvas, poem, emotion, userInput) => {
  try {
    ctx.save()

    // 设置字体
    ctx.textAlign = 'center'
    ctx.textBaseline = 'middle'

    // 绘制情绪标签 - 放在上面
    ctx.font = 'bold 28px "KaiTi", "楷体", serif'
    ctx.fillStyle = 'white'
    ctx.strokeStyle = 'rgba(0, 0, 0, 0.8)'
    ctx.lineWidth = 2
    const emotionY = canvas.height * 0.15
    ctx.strokeText(`— ${emotion} —`, canvas.width / 2, emotionY)
    ctx.fillText(`— ${emotion} —`, canvas.width / 2, emotionY)

    // 绘制诗句 - 使用格式化函数确保四行显示
    const lines = formatPoemLines(poem)
    const lineHeight = 60
    const startY = canvas.height * 0.35

    ctx.fillStyle = 'white'
    ctx.font = 'bold 36px "KaiTi", "楷体", serif'
    ctx.strokeStyle = 'rgba(0, 0, 0, 0.8)'
    ctx.lineWidth = 2

    lines.forEach((line, index) => {
      const y = startY + index * lineHeight
      ctx.strokeText(line, canvas.width / 2, y)
      ctx.fillText(line, canvas.width / 2, y)
    })

    // 绘制用户输入 - 放在下面，限制20个字
    if (userInput && userInput.trim()) {
      const displayInput = userInput.length > 20 ? userInput.substring(0, 20) + '...' : userInput
      ctx.font = '20px "KaiTi", "楷体", serif'
      ctx.fillStyle = 'rgba(255, 255, 255, 0.9)'
      const inputY = startY + lines.length * lineHeight + 60
      ctx.fillText(`"${displayInput}"`, canvas.width / 2, inputY)
    }

    // 绘制底部信息
    ctx.font = '16px "KaiTi", "楷体", serif'
    ctx.fillStyle = 'rgba(255, 255, 255, 0.7)'
    const currentTime = new Date().toLocaleDateString('zh-CN')
    ctx.fillText(`心语国韵 · ${currentTime}`, canvas.width / 2, canvas.height - 30)

    ctx.restore()
    console.log('✅ 分享卡片内容绘制完成')

  } catch (error) {
    console.error('❌ 绘制分享卡片内容失败:', error)
    ctx.restore()
    throw error
  }
}

/**
 * 获取预生成的分享卡片
 * @param {Object} params - 查询参数
 * @returns {string|null} - 分享卡片的data URL
 */
const getPregeneratedShareCard = ({ poem, emotion, userInput }) => {
  const cacheKey = `${poem}-${emotion}-${userInput}`.slice(0, 100)
  return shareCardCache.get(cacheKey) || null
}

/**
 * 清理过期缓存
 * @param {number} maxSize - 最大缓存数量
 */
const cleanupCache = (maxSize = 10) => {
  if (shareCardCache.size > maxSize) {
    const entries = Array.from(shareCardCache.entries())
    // 保留最新的缓存项
    const toKeep = entries.slice(-maxSize)
    shareCardCache.clear()
    toKeep.forEach(([key, value]) => {
      shareCardCache.set(key, value)
    })
  }

  if (backgroundImageCache.size > maxSize) {
    const entries = Array.from(backgroundImageCache.entries())
    const toKeep = entries.slice(-maxSize)
    // 释放旧的blob URLs
    entries.slice(0, -maxSize).forEach(([_, url]) => {
      if (url.startsWith('blob:')) {
        URL.revokeObjectURL(url)
      }
    })
    backgroundImageCache.clear()
    toKeep.forEach(([key, value]) => {
      backgroundImageCache.set(key, value)
    })
  }
}

/**
 * 立即触发分享卡片预生成
 * @param {Object} data - 生成数据
 */
const triggerShareCardPregeneration = async (data) => {
  try {
    // 异步预生成，不阻塞主流程
    pregenerateShareCard(data).then(() => {
      // 预生成完成后清理缓存
      cleanupCache()
    })
  } catch (error) {
    console.warn('⚠️ 分享卡片预生成触发失败:', error)
  }
}

/**
 * 获取性能统计数据
 * @returns {Object} - 性能统计信息
 */
const getPerformanceStats = () => {
  updateStats()
  return { ...performanceStats }
}

/**
 * 订阅性能数据更新
 * @param {Function} listener - 监听器函数
 */
const subscribeToPerformanceUpdates = (listener) => {
  performanceListeners.add(listener)
}

/**
 * 取消订阅性能数据更新
 * @param {Function} listener - 监听器函数
 */
const unsubscribeFromPerformanceUpdates = (listener) => {
  performanceListeners.delete(listener)
}

/**
 * 重置性能统计
 */
const resetPerformanceStats = () => {
  performanceStats = {
    totalRequests: 0,
    cacheHits: 0,
    cacheMisses: 0,
    hitRate: 0,
    avgGenerationTime: 0,
    avgRetrievalTime: 0,
    currentCacheSize: 0,
    recentActivity: [],
    generationTimes: [],
    retrievalTimes: []
  }
  addActivity('system', '性能统计已重置', 0)
}

export {
  pregenerateShareCard,
  getPregeneratedShareCard,
  triggerShareCardPregeneration,
  cleanupCache,
  getPerformanceStats,
  subscribeToPerformanceUpdates,
  unsubscribeFromPerformanceUpdates,
  resetPerformanceStats
}

export default {
  pregenerateShareCard,
  getPregeneratedShareCard,
  triggerShareCardPregeneration,
  cleanupCache,
  getPerformanceStats,
  subscribeToPerformanceUpdates,
  unsubscribeFromPerformanceUpdates,
  resetPerformanceStats
}